package com.hmdp.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import com.hmdp.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static com.hmdp.utils.RedisConstants.FEED_KEY;
import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;
    @Autowired
    private IFollowService followService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {    //保存博客的同时推送到粉丝的收件箱
        // 获取登录用户
        UserVO userVO = UserHolder.getUser();
        blog.setUserId(userVO.getId());//登录用户就是博主，博主发了一篇笔记，所以blog的用户id是当前登录人员，是博主
        // 保存探店博文
        boolean isSuccess = blogService.save(blog);
        if(isSuccess){
            return Result.fail("保存博客失败！");
        }
        // 查询笔记的所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", userVO.getId()).list();//要把博主发布的笔记都推送给关注他的人，所以在查关联表的时候，此时博主id是follow_user_id,是被关注的一方；而且是查出来的结果再.list而不是查出来一个list
        // 推送笔记给所有粉丝
        for(Follow follow:follows){
            //获取所有粉丝id
            Long userId = follow.getUserId();//follow表里此时粉丝是user_id,博主是follow_user_id,所以是getUserId
            //推送（只推送blog的id节省内存）
            String key = FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 根据博客id给博客点赞
     * @param id
     * @return
     */
    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        return blogService.likeBlog(id);
    }

    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 获取登录用户
        UserVO userVO = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", userVO.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        return blogService.queryHotBlog(current);
    }

    /**
     * 根据blog的id查询blog内容
     */
    @GetMapping("/id")
    public Result queryBlogById(@PathVariable Long id){
        Blog blog =blogService.queryBlogById(id);
        return Result.ok(blog);
    }

    /**
     * 点赞列表排行榜
     * @param id
     * @return
     */
    @PutMapping("/likes/{id}")
    public Result queryBloglikes(@PathVariable("id") Long id) {
        return blogService.queryBloglikes(id);
    }

    // BlogController  根据id查询博主的探店笔记
    @GetMapping("/of/user")
    public Result queryBlogByUserId(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam("id") Long id) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }
}
